
#include <QApplication>
#include <QtGlobal>

#include <cstdlib> 
#include <iostream>

#include <stdio.h>

#include "serial.hpp"
#include "tips.hpp"

using namespace std;

Serial::Serial(const QString& fileName) : deviceFile(fileName)
{

    if (!deviceFile.open(QIODevice::ReadOnly | QIODevice::WriteOnly)) {
	cerr << "failed to open serial device: " << qPrintable(deviceFile.errorString()) << endl;
	exit(1);
    }

    io.setDevice(&deviceFile);
    io.setVersion(QDataStream::Qt_4_3);
    io.setByteOrder(QDataStream::BigEndian);
}

void Serial::run()
{
    quint8 packetId;

    forever {
	io >> packetId;
	if (tips::DLE == packetId) {
	    io >> packetId;
	    if (tips::DLE == packetId) {
		continue;
	    } else if (tips::ETX == packetId) {
		continue;
	    } else {
		parsePacket(packetId);
	    }
	}
    }

}

void Serial::parsePacket(quint8 packetId)
{

    if (0x8f == packetId) {
	cerr << "Got packet\n";
	Packet_0x8F_AB *packet = new Packet_0x8F_AB(io);
	printf("date = %d:%d:%d\n", packet->day, packet->month, packet->year);
    } else {
	return;
    }
}

